﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.

using Sheego.Service.X400.Scheduler.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Scheduler.Impl
{
    public class Scheduler : IScheduler
    {

        private ISchedulerLogger Logger;
        public Scheduler(ISchedulerLogger logger)
        {
            this.Logger = logger;
            ShouldRun = true;
        }

        #region IScheduler Members

        public bool ShouldRun { get; set; }

        private IList<IJob> _jobs = new List<IJob>();
        public IList<IJob> Jobs
        {
            get { return _jobs; }
        }

       
        void IScheduler.Run()
        {
            while (ShouldRun)
            {
                Step(DateTime.Now);
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
        }

        private int lastHour = -1;
        private int lastMinute = -1;
        public void Step(DateTime current)
        {
            if (current == new DateTime(0))
                throw new ArgumentOutOfRangeException("current"); 

            int hour = current.Hour;
            int minute = current.Minute;


            if (lastHour == hour && lastMinute == minute) return; //Nur einmal pro Zyklus ausführen
            lastHour = hour;
            lastMinute = minute;

            foreach (var job in Jobs)
            {
                if (job.Disabled) continue;
                if (!job.Match(hour, minute)) continue;

                Logger.Info("Starting job {0}", job.Name);
                int returnCode = job.Exec();
             
                //Job wird disabled, weil er einen harten Fehler wirft
                if (returnCode > 0)
                {
                    Logger.Error("Disabling job {0}, return code was {1}", job.Name, returnCode);
                    job.Disabled = true;
                }
                if (returnCode < 0)
                {
                    Logger.Error("Job {0} returned {1}", job.Name, returnCode);
                }

            }


        }

        #endregion

      

      
    }
}
